package com.simple.piger.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.simple.piger.entity.InviteCompanyEmp;
import com.simple.piger.utils.AjaxResult;
import com.simple.piger.utils.IdUtil;
import com.simple.piger.utils.PasswordUtils;
import com.simple.piger.utils.PublicUtil;
import com.simple.piger.constant.AjaxCode;
import com.simple.piger.dto.resp.SysUserListRespDto;
import com.simple.piger.entity.ApplyUser;
import com.simple.piger.entity.CmsSysUser;
import com.simple.piger.entity.CmsSysUserRole;
import com.simple.piger.exception.BusinessException;
import com.simple.piger.mapper.CmsSysUserMapper;
import com.simple.piger.service.CmsSysUserRoleService;
import com.simple.piger.service.CmsUserService;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cglib.core.CollectionUtils;
import org.springframework.cglib.core.Transformer;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author baolw
 */
@Service
public class CmsUserServiceImpl extends ServiceImpl<CmsSysUserMapper , CmsSysUser> implements CmsUserService {
    @Autowired
    private CmsSysUserRoleService cmsSysUserRoleService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult<String> login(String userName, String password, String tokenSession) throws Exception {
        // 获取登陆用户信息
        EntityWrapper<CmsSysUser> ew_cmsSysUser = new EntityWrapper<>();
        ew_cmsSysUser.eq("username", userName);
        CmsSysUser cmsSysUser = this.selectOne(ew_cmsSysUser);
        System.out.println(PasswordUtils.getPwd(password, cmsSysUser.getSalt()));
        if (!PasswordUtils.getPwd(password, cmsSysUser.getSalt()).equals(cmsSysUser.getPassword())){
            return new AjaxResult<>(-1, "密码不正确");
        }
        // 更新用户最后一次的登陆信息
        cmsSysUser.setSessionToken(tokenSession);
        cmsSysUser.setLastLogin(new Date());
        Boolean bool = this.updateById(cmsSysUser);
        if (!bool) {
            throw new Exception("登录信息保存失败！");
        }
        return new AjaxResult<>(200, "登入成功", cmsSysUser.getId());
    }

    @Override
    public int getUserListCount(Integer roleId,
                                Boolean locked) {
        return this.baseMapper.selUserListCount(roleId, locked);
    }

    @Override
    public List<SysUserListRespDto> getUserList(Integer roleId,
                                                Boolean locked,
                                                Integer page,
                                                Integer limit) {
        Integer start = PublicUtil.getPageStart(page, limit);
        return this.baseMapper.selUserList( roleId, locked, start, limit);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void resetUserPwd(String id) {
        /************************************************************* 修改帐号 ************************************************************/
        // 获取登陆用户信息
        CmsSysUser cmsSysUser = this.selectById(id);
        // 初始密码为6位随机数
        String randomPassWord = "112233";
        // 生成MD5密码
        String password = PasswordUtils.getPwd(randomPassWord, cmsSysUser.getSalt());
        // 修改帐号信息
        cmsSysUser.setPassword(password);
        Boolean bool = this.updateById(cmsSysUser);
        if (!bool) {
            throw new BusinessException("帐号信息修改失败！");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String addUser(CmsSysUser cmsSysUser,
                          String[] userRolesAdd) {
        /************************************************************* 前置校验 ************************************************************/
        // 判定创建的帐号是否存在
        EntityWrapper<CmsSysUser> ew_sameCmsSysUser = new EntityWrapper<>();
        ew_sameCmsSysUser.eq("username", cmsSysUser.getUsername());
        CmsSysUser sameCmsSysUser = this.selectOne(ew_sameCmsSysUser);
        if (sameCmsSysUser != null) {
            return "该帐号已存在！";
        }
        /************************************************************* 创建帐号 ************************************************************/
        // 生成盐
        String salt = RandomStringUtils.randomAlphanumeric(10);
        // 初始密码为6位随机数
        String randomPassWord = "112233";
        // 生成MD5密码
        String password = PasswordUtils.getPwd(randomPassWord, salt);
        // 新增帐号信息
        cmsSysUser.setId(IdUtil.getId());
        cmsSysUser.setPassword(password);
        cmsSysUser.setSalt(salt);
        cmsSysUser.setPhone(cmsSysUser.getUsername());
        cmsSysUser.setLocked(false);
        cmsSysUser.setCreateDate(new Date());
        Boolean bool = this.insert(cmsSysUser);
        if (!bool) {
            throw new BusinessException("帐号信息新增失败！");
        }
        // 新增用户的角色信息
        List<CmsSysUserRole> add_cmsSysUserRoles = new ArrayList<>();
        for (int i=0;i<userRolesAdd.length;i++) {
            CmsSysUserRole cmsSysUserRole = new CmsSysUserRole();
            cmsSysUserRole.setUserId(cmsSysUser.getId());
            cmsSysUserRole.setRoleId(Integer.parseInt(userRolesAdd[i]));
            add_cmsSysUserRoles.add(cmsSysUserRole);
        }
        if (add_cmsSysUserRoles.size() > 0) {
            Boolean bool1 = cmsSysUserRoleService.insertBatch(add_cmsSysUserRoles);
            if (!bool1) {
                throw new BusinessException("帐号与角色关联信息新增失败！");
            }
        }
        return null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String editUser(CmsSysUser cmsSysUser,
                           String[] userRolesAdd,
                           String[] userRolesDel) {
        /************************************************************* 修改帐号 ************************************************************/
        // 修改帐号信息
        Boolean bool = this.updateById(cmsSysUser);
        if (!bool) {
            throw new BusinessException("帐号信息修改失败！");
        }
        /************************************************************* 修改帐号与角色关联信息 ************************************************************/
        // 新增用户的角色信息
        if (userRolesAdd != null && userRolesAdd.length > 0) {
            List<CmsSysUserRole> add_cmsSysUserRoles = new ArrayList<>();
            for (int i=0;i<userRolesAdd.length;i++) {
                CmsSysUserRole cmsSysUserRole = new CmsSysUserRole();
                cmsSysUserRole.setUserId(cmsSysUser.getId());
                cmsSysUserRole.setRoleId(Integer.parseInt(userRolesAdd[i]));
                add_cmsSysUserRoles.add(cmsSysUserRole);
            }
            if (add_cmsSysUserRoles.size() > 0) {
                Boolean bool1 = cmsSysUserRoleService.insertBatch(add_cmsSysUserRoles);
                if (!bool1) {
                    throw new BusinessException("帐号与角色关联信息新增失败！");
                }
            }
        }
        // 删除用户的角色信息
        if (userRolesDel != null && userRolesDel.length > 0) {
            EntityWrapper<CmsSysUserRole> ew = new EntityWrapper<>();
            ew.in("role_id", userRolesDel);
            ew.eq("user_id", cmsSysUser.getId());
            List<CmsSysUserRole> list = cmsSysUserRoleService.selectList(ew);
            Boolean bool2 = cmsSysUserRoleService.deleteBatchIds(CollectionUtils.transform(list, new Transformer() {
                @Override
                public Object transform(Object o) {
                    return ((CmsSysUserRole)o).getId();
                }
            }));
            if (!bool2) {
                throw new BusinessException("帐号与角色关联信息删除失败！");
            }
        }
        return null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxCode editPWD(String id,
                            String old_password,
                            String new_password) {
        // 获取登陆用户信息
        CmsSysUser cmsSysUser = this.selectById(id);
        // 校验输入的原密码
        String olePassword = PasswordUtils.getPwd(old_password, cmsSysUser.getSalt());
        if (!cmsSysUser.getPassword().equals(olePassword)) {
            return AjaxCode.OLD_PASS_ERROR;
        }
        // 校验原密码和新密码不重复
        String newPassword = PasswordUtils.getPwd(new_password, cmsSysUser.getSalt());
        if (olePassword.equals(newPassword)) {
            return AjaxCode.SAME_PASS_ERROR;
        }
        // 保存新密码
        cmsSysUser.setPassword(newPassword);
        boolean bool = this.updateById(cmsSysUser);
        if (!bool) {
            throw new BusinessException("密码修改失败！");
        }
        return null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxCode register(String username, String password, String roleId, String companyId) {
        EntityWrapper<CmsSysUser> ew = new EntityWrapper<>();
        ew.eq("username", username);
        CmsSysUser cmsSysUser = this.selectOne(ew);
        if (null != cmsSysUser) {
            return AjaxCode.REGISTER_REPEAT;
        }
        cmsSysUser = new CmsSysUser();
        cmsSysUser.setId(IdUtil.getId());
        cmsSysUser.setUsername(username);
        cmsSysUser.setSalt(RandomStringUtils.randomAlphanumeric(6));
        cmsSysUser.setPassword(PasswordUtils.getPwd(password, cmsSysUser.getSalt()));
        cmsSysUser.setCreateDate(new Date());
        if (!cmsSysUser.insert()) {
            throw new BusinessException("注册失败！");
        }
        // 新增用户的角色信息
        CmsSysUserRole cmsSysUserRole = new CmsSysUserRole();
        cmsSysUserRole.setUserId(cmsSysUser.getId());
        cmsSysUserRole.setRoleId(Integer.parseInt(roleId));
        if (!cmsSysUserRole.insert()) {
            throw new BusinessException("注册失败！");
        }
        ApplyUser applyUser = new ApplyUser();
        applyUser.setId(IdUtil.getId());
        applyUser.setName(cmsSysUser.getUsername());
        applyUser.setImg("https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=4034879928,1229713244&fm=26&gp=0.jpg");
        applyUser.setCmsSysUserId(cmsSysUser.getId());
        if (!applyUser.insert()) {
            throw new BusinessException("注册失败！");
        }
        if (StringUtils.isNotBlank(companyId)) {
            InviteCompanyEmp companyEmp = new InviteCompanyEmp();
            companyEmp.setCreateTime(new Date());
            companyEmp.setDeleteFlag("0");
            companyEmp.setId(IdUtil.getId());
            companyEmp.setInviteCompanyId(companyId);
            companyEmp.setApplyUserId(applyUser.getId());
            companyEmp.insert();
        }
        return null;
    }
}
